<template>
  <div class="collection">
    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="500px"
      center
      @close="addDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select style="width: 390px" v-model="addForm.gender" placeholder="请选择">
            <el-option
              v-for="item in sex"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="等级" prop="rank">
          <el-select style="width: 390px" v-model="addForm.rank" placeholder="请选择">
            <el-option
              v-for="item in ranks"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="500px"
      center
      @close="editDialogClosed"
    >
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="editForm.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="editForm.password" disabled></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-select style="width: 390px" v-model="editForm.gender" placeholder="请选择">
            <el-option
              v-for="item in sex"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="等级" prop="rank">
          <el-select style="width: 390px" v-model="editForm.rank" placeholder="请选择">
            <el-option
              v-for="item in ranks"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <div class="filter-container">
        <el-input
          v-model="queryInfo.name"
          placeholder="姓名"
          style="width: 100px;"
          class="filter-item"
          @keyup.enter.native="getUserList"
        />
        <el-select style="width: 150px" v-model="queryInfo.gender" placeholder="性别" clearable>
          <el-option v-for="item in sex" :key="item.value" :label="item.label" :value="item.label"></el-option>
        </el-select>
        <el-select
          v-model="queryInfo.rank"
          placeholder="等级"
          clearable
          style="width: 90px"
          class="filter-item"
        >
          <el-option
            v-for="item in ranks"
            :key="item.value"
            :label="item.label"
            :value="item.label"
          ></el-option>
        </el-select>

        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="getUserList"
        >Search</el-button>
        <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        <el-button
          :loading="downloadLoading"
          type="primary"
          icon="el-icon-document"
          @click="handleDownload"
        >导出excel</el-button>
      </div>

      <div class="table-box">
        <el-table
          border
          stripe
          ref="multipleTable"
          :data="userlist"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="expand">
            <template slot-scope="scope">
              <pre>{{ scope.row }}</pre>
            </template>
          </el-table-column>
          <!-- <el-table-column type="index"></el-table-column> -->

          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column prop="_id" label="ID" width="330px" align="center"></el-table-column>
          <el-table-column prop="name" label="姓名" width align="center"></el-table-column>
          <el-table-column prop="gender" label="性别" width align="center"></el-table-column>
          <el-table-column label="等级" width align="center">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.rank === '普通'" type="info">普通</el-tag>
              <el-tag v-else-if="scope.row.rank === '高级'" type="warning">高级</el-tag>
              <el-tag v-else type="danger">管理员</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" :formatter="setDate" label="创建时间" width align="center"></el-table-column>
          <el-table-column prop="changeTime" :formatter="setDate" label="修改时间" width align="center"></el-table-column>

          <!-- 演示数据 -->
          <!-- <el-table-column prop="dataName" label="商品" width align="center"></el-table-column>
          <el-table-column prop="creator" label="创建人" width align="center"></el-table-column>
          <el-table-column prop="createTime" label="创建时间" width align="center"></el-table-column>
          <el-table-column prop="changeTime" label="修改时间" width align="center"></el-table-column>-->
          <el-table-column label="操作" width="200" align="center">
            <template slot-scope="scope">
              <!-- {{scope.row}} -->
              <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="small"
                  @click="removeUserById(scope.row._id)"
                ></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="编辑" placement="top" :enterable="false">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="small"
                  @click="showEditDialog(scope.row._id)"
                ></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="查看" placement="top" :enterable="false">
                <el-button
                  type="success"
                  icon="el-icon-search"
                  size="small"
                  @click="handleOperate(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
  </div>
</template>

<script>
import moment from 'moment'
export default {
  name: 'Collection',
  data() {
    // 验证邮箱的规则
    // var checkEmail = (rule, value, cb) => {
    //   // 验证邮箱的正则表达式
    //   const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

    //   if (regEmail.test(value)) {
    //     // 合法的邮箱
    //     return cb()
    //   }

    //   cb(new Error('请输入合法的邮箱'))
    // }

    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^1[3456789]\d{9}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }

    return {
      tableData: [
        {
          dataName: '商品1',
          creator: 'Admin',
          createTime: '2019-03-01 12:33:10',
          changeTime: '2019-03-02 15:00:06'
        },
        {
          dataName: '商品2',
          creator: 'Admin',
          createTime: '2019-02-03 13:35:09',
          changeTime: '2019-02-14 11:06:11'
        },
        {
          dataName: '商品3',
          creator: 'Admin',
          createTime: '2019-01-11 10:33:55',
          changeTime: '2019-02-02 12:00:03'
        },
        {
          dataName: '商品4',
          creator: 'Admin',
          createTime: '2019-01-01 22:55:44',
          changeTime: '2019-01-02 15:00:06'
        },
        {
          dataName: '商品5',
          creator: 'Admin',
          createTime: '2018-11-16 11:33:14',
          changeTime: '2018-12-02 15:55:06'
        },
        {
          dataName: '商品6',
          creator: 'Admin',
          createTime: '2018-10-21 11:33:32',
          changeTime: '2018-12-09 11:15:26'
        },
        {
          dataName: '商品7',
          creator: 'Admin',
          createTime: '2018-08-26 16:22:25',
          changeTime: '2018-12-02 15:44:23'
        },
        {
          dataName: '商品8',
          creator: 'Admin',
          createTime: '2018-08-23 10:43:10',
          changeTime: '2018-09-22 17:25:25'
        },
        {
          dataName: '商品9',
          creator: 'Admin',
          createTime: '2018-07-17 11:33:35',
          changeTime: '2018-11-02 15:55:23'
        },
        {
          dataName: '商品10',
          creator: 'Admin',
          createTime: '2018-05-19 11:34:35',
          changeTime: '2018-09-04 18:31:21'
        }
      ],
      sex: [
        {
          value: -1,
          label: '保密'
        },
        {
          value: 0,
          label: '男'
        },
        {
          value: 1,
          label: '女'
        }
      ],
      rank: '',
      ranks: [
        {
          value: 1,
          label: '高级'
        },
        {
          value: 0,
          label: '管理员'
        },
        {
          value: 2,
          label: '普通'
        }
      ],
      // 获取用户列表的参数对象
      queryInfo: {
        name: '',
        rank: '',
        gender: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 10
      },
      userlist: [],
      total: 0,
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        name: '',
        gender: '',
        rank: '',
        password: ''
      },
      list: null,
      multipleSelection: [],
      filename: '',
      downloadLoading: false,

      // 添加表单的验证规则对象
      addFormRules: {
        name: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名的长度在3~10个字符之间',
            trigger: 'blur'
          }
        ],
        // email: [
        //   { required: true, message: '请输入邮箱', trigger: 'blur' },
        //   { validator: checkEmail, trigger: 'blur' }
        // ],
        tel: [
          { required: true, message: '请输入密码号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的用户信息对象
      editForm: {},
      // 修改表单的验证规则对象
      editFormRules: {
        // email: [
        //   { required: true, message: '请输入用户邮箱', trigger: 'blur' },
        //   { validator: checkEmail, trigger: 'blur' }
        // ],
        tel: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 导出
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 下载
    handleDownload() {
      if (this.multipleSelection.length) {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = [
            'ID',
            '姓名',
            '性别',
            '密码',
            '等级',
            '创建时间',
            '修改时间'
          ]
          const filterVal = [
            '_id',
            'name',
            'gender',
            'password',
            'rank',
            'createTime',
            'changeTime'
          ]
          const list = this.multipleSelection
          const data = this.formatJson(filterVal, list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: this.filename
          })
          this.$refs.multipleTable.clearSelection()
          this.downloadLoading = false
        })
      } else {
        this.$message({
          message: 'Please select at least one item',
          type: 'warning'
        })
      }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    handleOperate(ele) {
      // console.log(ele)
      this.$router.push({
        path: '/tables/details'
      })
    },
    setDate(row, column) {
      var newdate = row[column.property]
      if (newdate === undefined) return
      return moment(newdate).format('YYYY-MM-DD HH:mm:ss')
    },
    // handleDelete() {
    //   this.$notify({
    //     title: '警告',
    //     message: '不能删除',
    //     duration: 2000,
    //     type: 'error'
    //   })
    // },
    // handleEdit() {
    //   this.$message({
    //     showClose: true,
    //     message: '没有编辑权限',
    //     duration: 2000,
    //     type: 'error'
    //   })
    // },
    async getUserList() {
      // this.$http.defaults.headers['IP'] = location.href.toString()
      // this.$http.defaults.headers['token'] = window.sessionStorage.getItem(
      //   'token'
      // )
      const { data: res } = await this.$http.get('/users', {
        params: this.queryInfo
      })
      // console.log(res)
      if (res.status !== 201) {
        return this.$message.error('获取用户列表失败！')
      }
      this.userlist = res.user
      this.total = res.total
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听 switch 开关状态的改变
    // async userStateChanged(userinfo) {
    //   console.log(userinfo)
    //   const { data: res } = await this.$http.put(
    //     `users/${userinfo.id}/state/${userinfo.mg_state}`
    //   )
    //   if (res.meta.status !== 200) {
    //     userinfo.mg_state = !userinfo.mg_state
    //     return this.$message.error('更新用户状态失败！')
    //   }
    //   this.$message.success('更新用户状态成功！')
    // },
    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击按钮，添加新用户
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        //     // 可以发起添加用户的网络请求
        const { data: res } = await this.$http.post('/addUser/', this.addForm)

        if (res.status !== 201) {
          this.$message.error('添加用户失败！')
        }

        this.$message.success('添加用户成功！')
        // 隐藏添加用户的对话框
        this.addDialogVisible = false
        //     // 重新获取用户列表数据
        this.getUserList()
      })
    },
    // 展示编辑用户的对话框
    async showEditDialog(id) {
      // console.log(id)
      const { data: res } = await this.$http.get('/user/', { params: id })

      if (res.status !== 201) {
        return this.$message.error('查询用户信息失败！')
      }
      // console.log(res.user[0]._id)
      this.editForm = res.user[0]
      this.editDialogVisible = true
    },
    // 监听修改用户对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    }, // 修改用户信息并提交
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        // 发起修改用户信息的数据请求
        const { data: res } = await this.$http.put('/user/', {
          _id: this.editForm._id,
          changeTime: new Date(),
          gender: this.editForm.gender,
          name: this.editForm.name,
          password: this.editForm.password,
          rank: this.editForm.rank
        })

        if (res.status !== 201) {
          return this.$message.error('更新用户信息失败！')
        }

        // 关闭对话框
        this.editDialogVisible = false
        // 刷新数据列表
        this.getUserList()
        // 提示修改成功
        this.$message.success('更新用户信息成功！')
      })
    },
    // 根据Id删除对应的用户信息
    async removeUserById(id) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      const { data: res } = await this.$http.delete('/user/', {
        data: { id: id }
      })

      if (res.status !== 201) {
        return this.$message.error('删除用户失败！')
      }
      this.$message.success('删除用户成功！')
      this.getUserList()
    }
  }
}
</script>

<style lang="stylus"></style>
